package com.muyu.cloud.common.many.datasource.factory;

import com.alibaba.druid.pool.DruidDataSource;
import com.muyu.cloud.common.many.datasource.domain.model.DataSourceInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @Author: DongZeLiang
 * @date: 2024/6/3
 * @Description: Druid工厂
 * @Version: 1.0
 */
@Log4j2
@Component
public class DruidDataSourceFactory {

    /**
     * @Description: 根据传递的数据源信息测试数据库连接
     * @Author Dongzl
     */
    public DruidDataSource create(DataSourceInfo dataSourceInfo) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceInfo.getUrl());
        druidDataSource.setUsername(dataSourceInfo.getUserName());
        druidDataSource.setPassword(dataSourceInfo.getPassword());
        druidDataSource.setBreakAfterAcquireFailure(true);
        druidDataSource.setConnectionErrorRetryAttempts(0);
        try {
            druidDataSource.getConnection(2000);
            log.info("{} -> 数据源连接成功", dataSourceInfo.getKey());
            return druidDataSource;
        } catch (SQLException throwables) {
            log.error("数据源 {} 连接失败,用户名：{}，密码 {}",dataSourceInfo.getUrl(),dataSourceInfo.getUserName(),dataSourceInfo.getPassword());
            return null;
        }
    }
}
